#include "GOTHusb.h"

#include "GOTHuart.h"

void USB_InitUSB(){
	// usb afzetten
	U1CONbits.USBEN = 0;
	
	// USB status led
	TRISAbits.TRISA2 = 0;
	LATAbits.LATA2 = 0;
	
#ifdef USB_HOST
	#warning USB module will be initialized in host mode
	U1CONbits.HOSTEN = 1;		// enable in host mode
	
	U1OTGCONbits.VBUSON = 0;
	U1OTGCONbits.OTGEN = 0;
	
	U1OTGCONbits.DPPULDWN = 1;	//Enable the D+ and D- pull-down resistors
	U1OTGCONbits.DMPULDWN = 1;
	U1OTGCONbits.DPPULUP = 0;	//Disable the D+ and Dpull-up resistors
	U1OTGCONbits.DMPULUP = 0;
	
	U1CONbits.SOFEN = 0 ; 	// disable SOF generation (we'll put it back on later)

	U1OTGIE = 0x00ff; 		// enable all OTG interrupts
	U1IE = 0x00ff;			// enable all USB interrupts
	U1EIE = 0x00ff;			// enable all USB errors
	
	IFS5bits.USB1IF = 0;	// clear global USB IF
	IEC5bits.USB1IE = 1;	// enable global USB interrupt
	//IPC21bits.USB1IP;
	
	U1CNFG1bits.UTEYE = 1;
#endif
}

void __attribute__((interrupt,no_auto_psv)) _USB1Interrupt(void){
	// check which interrupt
	USB_SetLed();
	UART_WriteBuffer((uint8 *)"USB\n",4);
	IFS5bits.USB1IF = 0; // clear interrupt flag
}

/** Use this function in CN_InitCN() to enable the USB over current detection.
 *
 */
void USB_EnableOCD(){
	TRISAbits.TRISA3 = 1;
	CNEN3bits.CN36IE = 1;
	CNPU3bits.CN36PUE = 0;
	CNPD3bits.CN36PDE = 0;
}
